package com.ny.config;

import org.apache.qpid.jms.JmsConnectionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jms.annotation.EnableJms;
import org.springframework.jms.config.DefaultJmsListenerContainerFactory;
import org.springframework.jms.connection.CachingConnectionFactory;

import javax.jms.ConnectionFactory;
import java.util.Date;

@Configuration
@EnableJms // 启用JMS功能
public class AmqpConfig {

    private static final Logger logger = LoggerFactory.getLogger(AmqpConfig.class);
    // 从配置文件读取AMQP接入地址
    @Value("${amqp.server.address:9afbe182c2.st1.iotda-app.cn-north-4.myhuaweicloud.com}")
    private String serverAddress;
    // 从配置文件读取accessKey
    @Value("${amqp.access.key:kH2WVFfG}")
    private String accessKey;
    // 从配置文件读取accessCode
    @Value("${amqp.access.code:3ZXLoH80dzQkXm0MP9vAXDDK0e50UaqJ}")
    private String accessCode;
    // 从配置文件读取队列名称
    @Value("${amqp.queue.name:sensor_queue}")
    private String queueName;
    // 从配置文件读取VHost
    @Value("${amqp.vhost:default}")
    private String vhost;
    // 从配置文件读取空闲超时时间(毫秒)
    @Value("${amqp.idle.timeout:30000}")
    private int idleTimeout;
    // 固定的时间戳，在应用启动时生成一次
    private final long timestamp = new Date().getTime();

    @Bean
    public ConnectionFactory connectionFactory() {
        // 构建连接URL
        String connectionUrl = String.format(
                "amqps://%s:5671?amqp.vhost=%s&amqp.idleTimeout=%d&amqp.saslMechanisms=PLAIN",
                serverAddress, vhost, idleTimeout
        );
        try {
            // 创建Qpid JMS连接工厂
            JmsConnectionFactory factory = new JmsConnectionFactory(connectionUrl);
            // 生成用户名（包含accessKey、固定时间戳）
            String username = String.format("accessKey=%s|timestamp=%d", accessKey, timestamp);
            // 设置用户名和密码
            factory.setUsername(username);
            factory.setPassword(accessCode);

            // 记录详细的连接配置信息
            logger.info("初始化AMQP连接工厂:");
            logger.info("  - 服务器地址: {}", serverAddress);
            logger.info("  - VHost: {}", vhost);
            logger.info("  - 空闲超时: {} ms", idleTimeout);
            logger.info("  - 队列名称: {}", queueName);
            logger.info("  - 用户名格式: accessKey=<key>|timestamp=<timestamp>");
            
            // 使用缓存连接工厂提高性能
            CachingConnectionFactory cachingFactory = new CachingConnectionFactory(factory);
            cachingFactory.setReconnectOnException(true); // 启用异常时自动重连
            
            logger.info("AMQP连接工厂创建成功");
            return cachingFactory;
        } catch (Exception e) {
            logger.error("创建AMQP连接工厂失败: {}", e.getMessage(), e);
            throw new RuntimeException("Failed to create AMQP connection factory", e);
        }
    }

    /**
     * 创建JMS监听器容器工厂
     */
    @Bean
    public DefaultJmsListenerContainerFactory jmsListenerContainerFactory(ConnectionFactory connectionFactory) {
        DefaultJmsListenerContainerFactory factory = new DefaultJmsListenerContainerFactory();
        factory.setConnectionFactory(connectionFactory);
        // 设置并发消费者数量，根据需要调整
        factory.setConcurrency("1-5");
        // 开启消息确认机制
        factory.setSessionAcknowledgeMode(javax.jms.Session.CLIENT_ACKNOWLEDGE);
        logger.debug("JMS监听器容器工厂已创建，连接工厂: {}", connectionFactory);
        return factory;
    }

    /**
     * 提供队列名称的Bean
     */
    @Bean
    public String queueName() {
        logger.debug("获取队列名称: {}", queueName);
        return queueName;
    }
}